package tianrun.ziguan.api.forecast.handler;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import tianrun.ziguan.api.forecast.exception.CodeException;
import tianrun.ziguan.api.forecast.exception.CommonErrorCode;
import tianrun.ziguan.api.forecast.util.ReturnMessage;


/** 全局异常 */
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {
    @SuppressWarnings("unused")
    private final static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ReturnMessage> validExceptionHandler(@Nullable MethodArgumentNotValidException valid) {
        ReturnMessage returnMessage = new ReturnMessage();
        String message = "参数校验异常,请检查";
        returnMessage.setMessage(CommonErrorCode.SYS_1001.getDescription());
        returnMessage.setResult(message);
        returnMessage.setStatusCode(CommonErrorCode.SYS_1001.getCode());
        return new ResponseEntity<>(returnMessage,HttpStatus.OK);
    }


    @ExceptionHandler(value = CodeException.class)
    public ResponseEntity<ReturnMessage> codeExceptionException(CodeException codeException) {
        ReturnMessage returnMessage = new ReturnMessage();
        String message = codeException.getMessage();
        if (StringUtils.isBlank(message)){
            returnMessage.setMessage(codeException.getErrorCode().getDescription());
        } else {
            returnMessage.setMessage(codeException.getMessage());
        }
        returnMessage.setStatusCode(codeException.getErrorCode().getCode());
        returnMessage.setResult("ERROR");
        return new ResponseEntity<>(returnMessage, HttpStatus.OK);
    }



}
